import React from 'react';
import { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from '@/lib/toast-with-audio';
import { cn } from '@/lib/utils';
import { useTheme } from '@/hooks/useTheme';
import { useSystem } from '@/contexts/systemContext';
import { useAudioNotification } from '@/hooks/useAudioNotification';
import { useMessages } from '@/contexts/MessageContext';
import { useAuth } from '@/contexts/authContext';
import DetailDrawer from '@/components/DetailDrawer';

interface HeaderProps {
  className?: string;
}

// 使用统一的消息存储，不再需要本地消息数据

export default function Header({ className = '' }: HeaderProps) {
  const navigate = useNavigate();
  const [selectedProject, setSelectedProject] = useState('电商系统项目群');
  const [searchQuery, setSearchQuery] = useState('');
  const [isMessagesOpen, setIsMessagesOpen] = useState(false);
  const [selectedMessage, setSelectedMessage] = useState<any>(null);
  const [isSystemDropdownOpen, setIsSystemDropdownOpen] = useState(false);
  const [isUserDropdownOpen, setIsUserDropdownOpen] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const { theme, toggleTheme, isDark } = useTheme();
  const { currentSystem, systems, switchSystem } = useSystem();
  const { playNewMessageNotification, playSystemNotification, playTaskNotification } = useAudioNotification();
  const { messages, unreadCount, markAsRead, markAllAsRead, addMessage } = useMessages();
  const { user, logout } = useAuth();
  
  const messagesRef = useRef<HTMLDivElement>(null);
  const systemDropdownRef = useRef<HTMLDivElement>(null);
  const userDropdownRef = useRef<HTMLDivElement>(null);
  
  // 模拟新消息到达 - 现在使用统一的消息存储
  useEffect(() => {
    // 模拟每30秒有新消息到达（仅用于演示）
    const interval = setInterval(() => {
      // 随机决定是否发送新消息（30%概率）
      if (Math.random() < 0.3) {
        const messageTypes = ['系统通知', '任务提醒', '项目更新', '缺陷提醒', '团队协作'];
        const randomType = messageTypes[Math.floor(Math.random() * messageTypes.length)];
        const isImportant = Math.random() < 0.2; // 20%概率是重要消息
        
        // 使用统一的消息存储添加新消息
        addMessage({
          type: randomType,
          title: `新的${randomType}`,
          content: `这是一条新的${randomType}消息，请及时处理。`,
          time: new Date().toLocaleString('zh-CN'),
          important: isImportant
        });
        
        // 播放新消息通知声音
        playNewMessageNotification(unreadCount + 1, isImportant);
        
        // 显示toast提示
        toast.info(`您有${unreadCount + 1}条未读消息，请及时查阅`);
      }
    }, 30000); // 30秒
    
    return () => clearInterval(interval);
  }, [playNewMessageNotification, addMessage, unreadCount]);
  
  // 点击外部关闭消息下拉、系统下拉和用户下拉
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (messagesRef.current && !messagesRef.current.contains(event.target as Node)) {
        setIsMessagesOpen(false);
      }
      if (systemDropdownRef.current && !systemDropdownRef.current.contains(event.target as Node)) {
        setIsSystemDropdownOpen(false);
      }
      if (userDropdownRef.current && !userDropdownRef.current.contains(event.target as Node)) {
        setIsUserDropdownOpen(false);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  
  const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      toast(`搜索: ${searchQuery}`);
    }
  };
  
  const handleMessageClick = () => {
    setIsMessagesOpen(!isMessagesOpen);
  };
  
  const handleSystemDropdownClick = () => {
    setIsSystemDropdownOpen(!isSystemDropdownOpen);
  };

  const handleUserDropdownClick = () => {
    setIsUserDropdownOpen(!isUserDropdownOpen);
  };

  const handleLogout = () => {
    logout();
    toast.success('已成功退出登录');
    setIsUserDropdownOpen(false);
  };
  
  const handleSystemSwitch = (systemId: string) => {
    switchSystem(systemId);
    setIsSystemDropdownOpen(false);
    toast.success(`已切换到${systems.find(s => s.id === systemId)?.name}`);
  };
  
  const handleViewAllMessages = () => {
    setIsMessagesOpen(false);
    navigate('/messages');
  };
  
  const handleMarkAsRead = (messageId: number, e: React.MouseEvent) => {
    e.stopPropagation();
    markAsRead(messageId);
    toast.success(`消息已标记为已读`);
  };
  
  const handleMarkAllAsRead = () => {
    markAllAsRead();
    toast.success('所有消息已标记为已读');
    setIsMessagesOpen(false);
  };
  
  const handleMessageDetail = (message: any) => {
    setSelectedMessage(message);
    setDrawerOpen(true);
    
    // 移除自动标记已读的逻辑，让用户手动决定是否标记已读
    // 如果消息未读，自动标记为已读
    // if (!message.read) {
    //   markAsRead(message.id);
    // }
  };
  
  const handleCloseDrawer = () => {
    setDrawerOpen(false);
    setSelectedMessage(null);
  };
  
  // 处理内容中的ID链接
  const renderContentWithLinks = (content: string, relatedId?: string, relatedType?: string) => {
    if (!content) return content;
    
    // 如果消息有相关的ID，优先使用relatedId
    if (relatedId && relatedType) {
      const idPattern = new RegExp(`(${relatedId})`, 'gi');
      const parts = content.split(idPattern);
      
      return parts.map((part, index) => {
        if (part === relatedId) {
          return (
            <span 
              key={index}
              className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 cursor-pointer underline"
              onClick={() => handleRelatedItemClick(relatedId, relatedType)}
            >
              {part}
            </span>
          );
        }
        return part;
      });
    }
    
    // 如果没有relatedId，尝试从内容中提取ID
    const patterns = [
      { pattern: /(需求ID:\s*)(REQ-\d+)/gi, type: 'requirement' },
      { pattern: /(任务ID:\s*)(TASK-\d+)/gi, type: 'task' },
      { pattern: /(Bug ID:\s*)(BUG-\d+)/gi, type: 'bug' },
      { pattern: /(REQ-\d+)/gi, type: 'requirement' },
      { pattern: /(TASK-\d+)/gi, type: 'task' },
      { pattern: /(BUG-\d+)/gi, type: 'bug' }
    ];
    
    let result = [content];
    
    patterns.forEach(({ pattern, type }) => {
      const newResult: any[] = [];
      result.forEach(item => {
        if (typeof item === 'string') {
          const parts = item.split(pattern);
          parts.forEach((part, index) => {
            if (pattern.test(part)) {
              newResult.push(
                <span 
                  key={`${type}-${index}`}
                  className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 cursor-pointer underline"
                  onClick={() => handleRelatedItemClick(part, type)}
                >
                  {part}
                </span>
              );
            } else {
              newResult.push(part);
            }
          });
        } else {
          newResult.push(item);
        }
      });
      result = newResult;
    });
    
    return result;
  };
  
  // 处理相关项目点击
  const handleRelatedItemClick = (id: string, type: string) => {
    closeMessageDetail();
    
    switch (type) {
      case 'requirement':
        navigate('/requirements');
        toast.success(`正在跳转到需求 ${id} 的详情页面`);
        break;
      case 'task':
        navigate('/tasks');
        toast.success(`正在跳转到任务 ${id} 的详情页面`);
        break;
      case 'bug':
        navigate('/bugs');
        toast.success(`正在跳转到Bug ${id} 的详情页面`);
        break;
      default:
        navigate('/messages');
        toast.info(`跳转到消息中心`);
    }
  };
  
  // 获取相关项目的图标
  const getRelatedItemIcon = (type: string) => {
    switch (type) {
      case 'requirement':
        return 'fa-solid fa-list-check';
      case 'task':
        return 'fa-solid fa-tasks';
      case 'bug':
        return 'fa-solid fa-bug';
      default:
        return 'fa-solid fa-file-lines';
    }
  };
  
  // 获取相关项目的类型名称
  const getRelatedItemTypeName = (type: string) => {
    switch (type) {
      case 'requirement':
        return '需求';
      case 'task':
        return '任务';
      case 'bug':
        return 'Bug';
      default:
        return '项目';
    }
  };
  
  return (
    <>
      <header className={cn("flex items-center justify-between py-3 px-6 bg-white dark:bg-gray-900 w-full", className)}>
        <div className="flex items-center">
          {/* 系统logo */}
          <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center mr-3">
            <i className="fa-solid fa-cubes text-white text-lg"></i>
          </div>
          
          {/* 系统名称和副标题 - 支持下拉切换 */}
          <div ref={systemDropdownRef} className="relative">
            <button 
              className="flex flex-col items-start py-2 px-3 bg-transparent border-0 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors text-left"
              onClick={handleSystemDropdownClick}
            >
              <div className="flex items-center space-x-2 mb-1">
                <i className={`${currentSystem.icon} ${currentSystem.color} text-lg`}></i>
                <span className="text-xl font-bold text-gray-800 dark:text-white">
                  {currentSystem.name}
                </span>
                <i className="fa-solid fa-chevron-down text-gray-500 text-sm"></i>
              </div>
              <span className="text-xs text-gray-500 dark:text-gray-400 ml-0">
                {currentSystem.description}
              </span>
            </button>
            
            {/* 系统下拉菜单 */}
            {isSystemDropdownOpen && (
              <div className="absolute top-full left-0 mt-2 w-64 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 z-50">
                <div className="p-3 border-b border-gray-200 dark:border-gray-700">
                  <h3 className="font-semibold text-gray-800 dark:text-gray-100 text-sm">
                    切换系统
                  </h3>
                </div>
                
                <div className="max-h-80 overflow-y-auto">
                  {systems.map((system) => (
                    <button
                      key={system.id}
                      className={`w-full flex items-center space-x-3 p-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors ${
                        system.id === currentSystem.id ? 'bg-blue-50 dark:bg-blue-900/20' : ''
                      }`}
                      onClick={() => handleSystemSwitch(system.id)}
                    >
                      <i className={`${system.icon} ${system.color} text-lg`}></i>
                      <div className="flex-1">
                        <div className="font-medium text-gray-800 dark:text-gray-100 text-sm">
                          {system.name}
                        </div>
                        <div className="text-xs text-gray-500 dark:text-gray-400">
                          {system.description}
                        </div>
                      </div>
                      {system.id === currentSystem.id && (
                        <i className="fa-solid fa-check text-blue-600 dark:text-blue-400"></i>
                      )}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
        
        <div className="flex items-center space-x-5">
          <div className="relative">
            <div className="bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center">
              <input 
                type="text" 
                placeholder="全局搜索..." 
                className="py-2 px-3 bg-transparent focus:outline-none w-48 text-sm leading-5 text-gray-800 dark:text-white placeholder-gray-500 dark:placeholder-gray-400"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={handleSearch}
              />
              <i className="fa-solid fa-magnifying-glass text-gray-500 dark:text-gray-400 mr-3 flex items-center justify-center"></i>
            </div>
          </div>
          
          <button 
            className="relative cursor-pointer p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
            onClick={toggleTheme}
            title={`切换到${isDark ? '明亮' : '暗黑'}主题`}
          >
            {isDark ? (
              <i className="fa-solid fa-sun text-xl text-yellow-500 flex items-center justify-center"></i>
            ) : (
              <i className="fa-solid fa-moon text-xl text-gray-600 dark:text-gray-400 flex items-center justify-center"></i>
            )}
          </button>
          
          {/* 消息图标和下拉菜单 */}
          <div ref={messagesRef} className="relative">
            <button 
              className="relative cursor-pointer p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
              onClick={handleMessageClick}
              title="消息中心"
            >
              <i className="fa-regular fa-bell text-xl text-gray-600 dark:text-gray-400 flex items-center justify-center"></i>
              {unreadCount > 0 && (
                <div className="absolute -top-1 -right-1">
                  <span className="relative flex min-w-5 h-5">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                    <span className="relative inline-flex min-w-5 h-5 px-1 items-center justify-center rounded-full bg-red-500 text-xs font-medium text-white whitespace-nowrap">
                      {unreadCount > 99 ? '99+' : unreadCount}
                    </span>
                  </span>
                </div>
              )}
            </button>
            
            {/* 消息下拉菜单 */}
            {isMessagesOpen && (
              <div className="absolute right-0 top-full mt-2 w-80 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 z-50">
                <div className="p-4 border-b border-gray-200 dark:border-gray-700">
                  <div className="flex justify-between items-center">
                    <h3 className="font-semibold text-gray-800 dark:text-gray-100">
                      未读消息 ({unreadCount})
                    </h3>
                    <button 
                      onClick={handleMarkAllAsRead}
                      className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 text-sm"
                    >
                      全部已读
                    </button>
                  </div>
                </div>
                
                <div className="max-h-80 overflow-y-auto">
                  {unreadCount === 0 ? (
                    <div className="p-8 text-center">
                      <i className="fa-regular fa-bell text-3xl text-gray-300 dark:text-gray-600 mb-3"></i>
                      <p className="text-gray-500 dark:text-gray-400">暂无未读消息</p>
                    </div>
                  ) : (
                    <div className="divide-y divide-gray-200 dark:divide-gray-700">
                      {messages.filter(msg => !msg.read).map((message) => (
                        <div 
                          key={message.id} 
                          className="p-4 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer transition-colors"
                          onClick={() => handleMessageDetail(message)}
                        >
                          <div className="flex justify-between items-start mb-2">
                            <span className={`px-2 py-1 text-xs font-medium rounded-full ${
                              message.type === '系统通知' ? 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300' :
                              message.type === '任务提醒' ? 'bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300' :
                              message.type === '项目更新' ? 'bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300' :
                              'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
                            }`}>
                              {message.type}
                            </span>
                            {message.important && (
                              <span className="px-2 py-1 bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 text-xs font-medium rounded-full">
                                重要
                              </span>
                            )}
                          </div>
                          
                          <h4 className="font-medium text-gray-800 dark:text-gray-100 mb-1 line-clamp-1">
                            {message.title}
                          </h4>
                          
                          <p className="text-sm text-gray-600 dark:text-gray-400 mb-2 line-clamp-2">
                            {message.content}
                          </p>
                          
                          <div className="flex justify-between items-center">
                            <span className="text-xs text-gray-500 dark:text-gray-400">
                              {message.time}
                            </span>
                            <button 
                              onClick={(e) => {
                                e.stopPropagation();
                                handleMarkAsRead(message.id, e);
                              }}
                              className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 text-xs"
                            >
                              标记已读
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
                
                <div className="p-3 border-t border-gray-200 dark:border-gray-700">
                  <button 
                    onClick={handleViewAllMessages}
                    className="w-full py-2 text-center text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 font-medium"
                  >
                    查看全部消息
                  </button>
                </div>
              </div>
            )}
          </div>
          
          {/* 用户头像和下拉菜单 */}
          <div ref={userDropdownRef} className="relative">
            <button 
              className="flex items-center space-x-2 p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
              onClick={handleUserDropdownClick}
            >
              <div className="w-9 h-9 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center text-blue-600 dark:text-blue-400 font-medium text-sm">
                {user?.avatar || '用'}
              </div>
              <div className="flex flex-col items-start">
                <span className="text-sm font-medium text-gray-800 dark:text-white">
                  {user?.username || '用户'}
                </span>
                <span className="text-xs text-gray-500 dark:text-gray-400">
                  {user?.role === 'admin' ? '管理员' : '普通用户'}
                </span>
              </div>
              <i className="fa-solid fa-chevron-down text-gray-500 text-sm"></i>
            </button>
            
            {/* 用户下拉菜单 */}
            {isUserDropdownOpen && (
              <div className="absolute right-0 top-full mt-2 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 z-50">
                <div className="p-3 border-b border-gray-200 dark:border-gray-700">
                  <div className="flex items-center space-x-3">
                    <div className="w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center text-blue-600 dark:text-blue-400 font-medium text-sm">
                      {user?.avatar || '用'}
                    </div>
                    <div>
                      <div className="font-medium text-gray-800 dark:text-white text-sm">
                        {user?.username || '用户'}
                      </div>
                      <div className="text-xs text-gray-500 dark:text-gray-400">
                        {user?.role === 'admin' ? '管理员' : '普通用户'}
                      </div>
                    </div>
                  </div>
                </div>
                
                <div className="p-1">
                  <button 
                    className="w-full flex items-center space-x-3 p-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 rounded-md transition-colors text-sm text-gray-700 dark:text-gray-300"
                    onClick={() => navigate('/settings')}
                  >
                    <i className="fa-solid fa-user text-gray-500 w-4"></i>
                    <span>个人设置</span>
                  </button>
                  
                  <button 
                    className="w-full flex items-center space-x-3 p-3 text-left hover:bg-gray-50 dark:hover:bg-gray-700 rounded-md transition-colors text-sm text-gray-700 dark:text-gray-300"
                    onClick={() => navigate('/help')}
                  >
                    <i className="fa-solid fa-circle-question text-gray-500 w-4"></i>
                    <span>帮助中心</span>
                  </button>
                  
                  <div className="border-t border-gray-200 dark:border-gray-700 my-1"></div>
                  
                  <button 
                    className="w-full flex items-center space-x-3 p-3 text-left hover:bg-red-50 dark:hover:bg-red-900/20 rounded-md transition-colors text-sm text-red-600 dark:text-red-400"
                    onClick={handleLogout}
                  >
                    <i className="fa-solid fa-right-from-bracket w-4"></i>
                    <span>退出登录</span>
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </header>

      {/* 消息抽屉 */}
      <DetailDrawer
        isOpen={drawerOpen}
        onClose={handleCloseDrawer}
        item={selectedMessage ? {
          id: selectedMessage.id,
          title: selectedMessage.title,
          type: 'message',
          priority: selectedMessage.important ? 'high' : 'normal',
          status: selectedMessage.read ? 'read' : 'unread',
          content: selectedMessage.content,
          sender: selectedMessage.sender || '系统',
          sendTime: selectedMessage.time,
          relatedId: selectedMessage.relatedId,
          relatedType: selectedMessage.relatedType
        } : null}
        type="message"
        onMarkAsRead={markAsRead} // 添加标记已读回调
      />
    </>
  );
}